package com.cll.pmis.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.cll.pmis.common.Constants;
import com.cll.pmis.common.exception.PmisException;
import com.cll.pmis.common.exception.TransactionException;
import com.cll.pmis.common.utils.CommonUtil;
import com.cll.pmis.entity.*;
import com.cll.pmis.mapper.PrescribeMapper;
import com.cll.pmis.service.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author chenliangliang
 * @since 2018-06-18
 */
@Service
public class PrescribeServiceImpl extends ServiceImpl<PrescribeMapper, Prescribe> implements IPrescribeService {


    private IOrderService orderService;
    private IDrugService drugService;
    private IOutputService outputService;

    protected PrescribeServiceImpl(IOrderService orderService, IDrugService drugService,
                                   IOutputService outputService) {
        this.orderService = orderService;
        this.drugService = drugService;
        this.outputService = outputService;
    }

    @Override
    @Transactional(rollbackFor = TransactionException.class)
    public Orders createPrescribe(Dossier dossier, String doctor, List<Prescribe> prescribes) {

        BigDecimal pay = new BigDecimal(0);
        StringBuilder sb=new StringBuilder();
        for (Prescribe prescribe : prescribes) {
            Integer drugId = prescribe.getDrugId();
            Drug drug = drugService.selectOne(new EntityWrapper<Drug>().eq("id", drugId));
            if (drug == null) {
                throw new PmisException("id为 " + drugId + " 的药品不存在");
            }

            if (drug.getNum() - drug.getFreeze() < prescribe.getNum()) {
                throw new PmisException("id为 " + drugId + " 的药品库存不足");
            }

            //冻结数量
            Integer freeze = drug.getFreeze() + prescribe.getNum();

            int res = drugService.getMapper().freezeNum(drugId, freeze);
            if (res != 1) {
                throw new TransactionException("冻结库存失败");
            }
            prescribe.setFrequency(prescribe.getFrequency()+"/天");
            sb.append(drug.getName()).append(",");
            pay = pay.add(drug.getSellPrice().multiply(new BigDecimal(drug.getNum())));
        }


        //出库
        Output output = new Output();
        output.setDoctor(doctor);
        output.setTaker(dossier.getUsername());
        output.setType(Constants.OUTPUT_TYPE_DOCTOR);
        output.setStatus(Constants.OUTPUT_STATUS_UNUSED);
        output.setCreateTime(new Date());
        if (!outputService.insert(output)) {
            throw new TransactionException("出库单生成失败");
        }
        //创建订单
        String orderNum = CommonUtil.timeStamp() + dossier.getId();
        Orders order = new Orders();
        order.setPay(pay);
        order.setDossierId(dossier.getId());
        order.setOrderId(orderNum);
        order.setSummary(sb.toString());
        order.setOutputId(output.getId());
        order.setStatus(Constants.ORDER_STATUS_UNPAY);
        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());

        if (!orderService.insert(order)) {
            throw new TransactionException("创建订单失败");
        }

        prescribes.forEach(it -> {
            it.setCreateTime(new Date());
            it.setOrderId(order.getId());});

        if (!insertBatch(prescribes)) {
            throw new TransactionException("插入开药信息异常");
        }

        return order;
    }

    @Override
    public PrescribeMapper getMapper() {
        return this.baseMapper;
    }
}
